﻿<%@ WebHandler Language="C#" Class="Json" %>

using System;
using System.Web;
using System.Data;
using System.Data.SqlClient;
using CommonLib.Extended;

/// <summary>
/// Json 的摘要说明
/// </summary>
public class Json : IHttpHandler
{
    static CommonLib.DbHelper.IDBhelper dbHelper = new CommonLib.DbHelper.Factory().IDBhelper;

    public void ProcessRequest(HttpContext context)
    {
        context.Response.ContentType = "text/plain";

        string mode = context.Request["mode"].ToString();
        string tn = context.Request["tn"].ToString();
        switch (mode)
        {
            case "NumSelect"://查询表中Grade数量
                {
                    string str = "["; string ls = "";
                    var sdr = dbHelper.ExecuteReader("select distinct Grade from " + tn + " order by Grade");
                    while (sdr.Read())
                    {
                        str += ls + "{\"num\":\"" + sdr["Grade"].ToString() + "\"}";
                        ls = ",";
                    }
                    sdr.Close();
                    str += "]";
                    context.Response.Write(str);
                    break;
                }
            case "select"://查询
                {
                    if (context.Request["Level"] != null && context.Request["id"] == null)//Grade 没有id的时候 
                    {
                        context.Response.Write(GetJsonTreeStatic(tn, context.Request["Level"].ToString()));
                    }
                    else
                    {
                        string pid = (context.Request["id"] != null) ? context.Request["id"].ToString() : "00000000-0000-0000-0000-000000000000";
                        string json = GetJsonTree(tn, pid);
                        if (json == "[]")
                        {
                            //dbHelper.ExecuteNonQuery(string.Format(@"INSERT INTO " + tn + @"
                            //              (pid, Grade, Leaf, Levels, Name, Target)
                            //        VALUES ('00000000-0000-0000-0000-000000000000', '1', 'True', '0001', '根节点', 'ClientFrame')"));
                            //json = GetJsonTree(tn, pid);
                        }
                        context.Response.Write(json);
                    }
                    break;
                }
            case "insert"://添加节点
                {
                    string Levels = ""; string Grade = "";
                    Layer_Level(tn, context.Request["pid"].ToString().Int(), out Grade, out Levels);

                    //string guid = id.NewGuid().ToString();
                    SqlParameter[] P = {
                                         //new SqlParameter("@id",guid),
                                         new SqlParameter("@pid", context.Request["pid"].ToString()),
                                         new SqlParameter("@Name", context.Request["Name"].ToString()),
                                         new SqlParameter("@Grade", Grade),
                                         new SqlParameter("@Levels", Levels),
                                         new SqlParameter("@Leaf", "True"),
                                         new SqlParameter("@Target", "ClientFrame"),
                                         new SqlParameter("@IsDelete", "0")};
                    string SqlStr = @"INSERT INTO " + tn + " (id,pid, Name, Grade, Levels,Leaf,Target,IsDelete) VALUES (@id,@pid, @Name, @Grade, @Levels,@Leaf,@Target,@IsDelete) SELECT @@IDENTITY AS id";
                    var id = dbHelper.ExecuteScalar(SqlStr, P).Int();

                    if (id > 0)
                    {
                        UpdateLeaf(context.Request["pid"].ToString().Int(), tn);//更新父节点 Leaf
                    }
                    context.Response.Write(id);
                    break;
                }
            case "edit":
                {
                    //编辑节点Name
                    dbHelper.ExecuteNonQuery("UPDATE " + tn + " SET Name = '" + context.Request["name"].ToString() + "' WHERE id = '" + context.Request["id"].ToString() + "'");
                    break;
                }
            case "delete"://删除节点
                {
                    var pid = dbHelper.ExecuteScalar("select pid from " + tn + " where id='" + context.Request["id"].ToString() + "'").Int();
                    if (pid != 0)//第一个根节点不能删除 
                    {
                        string Layer = dbHelper.ExecuteScalar("select Levels from " + tn + " where id='" + context.Request["id"].ToString() + "'");
                        //dbHelper.ExecuteNonQuery("DELETE FROM " + tn + " WHERE (id = '" + context.Request["id"].ToString() + "')"); 
                        dbHelper.ExecuteNonQuery("UPDATE " + tn + " SET IsDelete = 1 WHERE (id = '" + context.Request["id"].ToString() + "')");
                        UpdateLeaf(pid, tn); //更新父节点 Leaf
                    }
                    break;
                }
            case "move"://移动节点
                {
                    string id = context.Request["id"].ToString();//移动的节点
                    var targetId = context.Request["targetId"].ToString().Int();//移动到的 父节点
                    string point = context.Request["point"].ToString();//移动方式
                    if (point == "append")//append,top,bottom； append:才做拖拽处理
                    {
                        int targetId_Level = Convert.ToInt32(dbHelper.ExecuteScalar("select Grade from " + tn + " where id='" + targetId + "'"));
                        string old_Layer = "";
                        int id_Level = 0;
                        var pid = 0;
                        var sdr = dbHelper.ExecuteReader("select pid,Levels,Grade from " + tn + " where id='" + id + "'");
                        if (sdr.Read())
                        {
                            id_Level = Convert.ToInt32(sdr["Grade"].ToString());
                            old_Layer = sdr["Levels"].ToString();
                            pid = sdr["pid"].ToString().Int();
                        }
                        sdr.Close();

                        if (pid != targetId)//移动本原来Levels 不做任何处理
                        {
                            //更新移动到的节点 Leaf
                            dbHelper.ExecuteNonQuery("UPDATE " + tn + " SET Leaf = 'False' WHERE id = '" + targetId + "'");

                            //更新移动节点 Grade Levels Leaf pid
                            string new_Layer = ""; string new_Level = "";
                            Layer_Level(tn, targetId, out new_Level, out new_Layer);
                            dbHelper.ExecuteNonQuery(string.Format("UPDATE {0} SET pid ='{1}', Grade ='{2}', Levels ='{3}' WHERE (id = '{4}')", tn, targetId, new_Level, new_Layer, id));

                            //更新子级 Levels Grade pid不变
                            string sqlstr = string.Format(@"UPDATE {5}
                                                    SET Grade = Grade+{1}, Levels ='{4}'+SUBSTRING(Levels, {2}, LEN(Levels) - {3})
                                                    WHERE (Levels LIKE '{0}%')", old_Layer, targetId_Level - id_Level + 1, old_Layer.Length + 1, old_Layer.Length, new_Layer, tn);
                            dbHelper.ExecuteNonQuery(sqlstr);
                            UpdateLeaf(pid, tn);
                        }
                        else//拖动到原来的父节点 不做处理
                        {
                            context.Response.Write("refresh");
                        }
                    }
                    break;
                }
            case "up"://上移
                {
                    //获取上一个相邻节点
                    string id = context.Request["id"].ToString();
                    string sqlstr = string.Format(@"SELECT  c.id,c.Levels
                                                    FROM {0} AS c INNER JOIN
                                                         {0} AS p ON c.pid = p.pid
                                                    WHERE (p.id = '{1}')
                                                    ORDER BY c.Levels", tn, id);
                    string 本Levels = ""; string upLevels = "";//string id = ""; 
                    var sdr = dbHelper.ExecuteReader(sqlstr);
                    while (sdr.Read())
                    {
                        if (sdr["id"].ToString() == id)
                        {
                            本Levels = sdr["Levels"].ToString();
                            break;
                        }
                        //id = sdr["id"].ToString();
                        upLevels = sdr["Levels"].ToString();
                    }
                    sdr.Close();
                    if (upLevels != "")
                    {
                        Up_Down(tn, upLevels, 本Levels);
                    }
                    else
                    {
                        context.Response.Write("NO");
                    }
                    break;
                }
            case "down"://下移
                {
                    //获取下一个相邻节点
                    string id = context.Request["id"].ToString();
                    string sqlstr = string.Format(@"SELECT  c.id,c.Levels
                                                    FROM {0} AS c INNER JOIN
                                                         {0} AS p ON c.pid = p.pid
                                                    WHERE (p.id = '{1}')
                                                    ORDER BY c.Levels DESC", tn, id);
                    string 本Levels = ""; string downLevels = "";//string id = "";
                    var sdr = dbHelper.ExecuteReader(sqlstr);
                    while (sdr.Read())
                    {
                        if (sdr["id"].ToString() == id)
                        {
                            本Levels = sdr["Levels"].ToString();
                            break;
                        }
                        //id = sdr["id"].ToString();
                        downLevels = sdr["Levels"].ToString();
                    }
                    sdr.Close();
                    if (downLevels != "")
                    {
                        Up_Down(tn, downLevels, 本Levels);
                    }
                    else
                    {
                        context.Response.Write("NO");
                    }
                    break;
                }
        }

    }


    /// <summary>
    /// 同Levels上移 下移
    /// </summary>
    /// <param name="Layer1">第一个节点Levels</param>
    /// <param name="Layer1">第二个节点Levels</param>
    private void Up_Down(string tn, string Layer1, string Layer2)
    {
        //把Layer1和子节点更新成 xxxx.xxxx.9999
        int lenght = Layer1.Length;
        string new_Layer1 = Layer1.Substring(0, Layer1.LastIndexOf(".")) + ".9999";
        dbHelper.ExecuteNonQuery(string.Format(@"UPDATE {0}
                                                SET Levels = '{4}'+SUBSTRING(Levels, {2}, LEN(Levels) - {3})
                                                WHERE (Levels LIKE '{1}%')", tn, Layer1, lenght + 1, lenght, new_Layer1));

        //更新Layer2和子节点为 Layer1 Levels结构
        lenght = Layer2.Length;
        dbHelper.ExecuteNonQuery(string.Format(@"UPDATE {0}
                                                SET Levels = '{4}'+SUBSTRING(Levels, {2}, LEN(Levels) - {3})
                                                WHERE (Levels LIKE '{1}%')", tn, Layer2, lenght + 1, lenght, Layer1));

        //更新Layer1和子节点为 Layer2 Levels结构
        lenght = Layer1.Length;
        dbHelper.ExecuteNonQuery(string.Format(@"UPDATE {0}
                                                SET Levels = '{4}'+SUBSTRING(Levels, {2}, LEN(Levels) - {3})
                                                WHERE (Levels LIKE '{1}%')", tn, new_Layer1, lenght + 1, lenght, Layer2));
    }

    /// <summary>
    /// 更新指定节点Leaf
    /// </summary>
    /// <param name="id">节点id</param>
    /// <param name="tn">表名</param>
    private void UpdateLeaf(int id, string tn)
    {
        int num = Convert.ToInt32(dbHelper.ExecuteScalar("select count(*) from " + tn + " where pid='" + id + "' and IsDelete=0"));
        string Leaf = num > 0 ? "False" : "True";
        dbHelper.ExecuteNonQuery("UPDATE " + tn + " SET Leaf = '" + Leaf + "' WHERE id = '" + id + "'");
    }

    /// <summary>
    /// 返回新添加接点的 Grade Levels 
    /// </summary>
    /// <param name="tn">表名</param>
    /// <param name="pguid">pid</param>
    /// <param name="Level">Grade</param>
    /// <param name="Layer">Levels</param>
    private void Layer_Level(string tn, int pid, out string Level, out string Layer)
    {
        string _Layer = "";//父级 Levels
        int _Level = 1; //子级 Grade
        int cMaxLayer = 1;//子级最大Levels
        string _pid = "0";

        var sdr = dbHelper.ExecuteReader(string.Format("SELECT Levels,Grade FROM " + tn + " WHERE id ='{0}'", pid));
        if (sdr.Read())
        {
            _Layer = sdr["Levels"].ToString();
            _Level = Convert.ToInt32(sdr["Grade"].ToString()) + 1;

            string 子级Levels = dbHelper.ExecuteScalar("SELECT TOP (1) Levels FROM " + tn + "  WHERE (Levels LIKE '" + sdr["Levels"].ToString() + ".____') ORDER BY Levels DESC");
            if (子级Levels != "")
            {
                cMaxLayer = Convert.ToInt32(子级Levels.Substring(子级Levels.LastIndexOf(".") + 1, 4)) + 1;
            }
        }
        sdr.Close();

        Layer = _Layer + "." + AddZero(cMaxLayer.ToString(), 4);
        Level = _Level.ToString();
    }

    /// <summary>
    /// 补齐Levels前面的 0
    /// </summary>
    /// <param name="num">要补齐的数字</param>
    /// <param name="length">长度</param>
    /// <returns></returns>
    private string AddZero(string num, int length)
    {
        string bl = "";//补零
        for (int i = 0; i < length - num.Length; i++)
        {
            bl += "0";
        }
        return bl + num;
    }


    /// <summary>
    /// 动态树json
    /// </summary>
    /// <returns></returns>
    public static string GetJsonTree(string tn, string pid)
    {
        string str = "[";
        var sdr = dbHelper.ExecuteReader("select id,Name,Grade,Target,Leaf,Levels from " + tn + " where pid='" + pid + "' and IsDelete = 0 order by Levels");
        while (sdr.Read())
        {
            if (str != "[") str += ",";
            str += "{";
            str += "\"id\":\"" + sdr["id"].ToString() + "\"";
            ////str += ",\"text\":\"" + sdr["Name"].ToString() + "【" + sdr["id"].ToString() + "】【" + sdr["Levels"].ToString() + "】\"";
            //str += ",\"text\":\"" + sdr["Name"].ToString() + "【" + sdr["id"].ToString() + "】\"";
            str += ",\"text\":\"" + sdr["Name"].ToString() + "\"";
            str += (sdr["Leaf"].ToString()) == "True" ? ",\"iconCls\":\"icon-tree_leaf\"" : "";

            //str += ",\"attributes\":{\"url\":\"" + sdr["链接"].ToString() + "\"";
            //str += ",\"target\":\"" + sdr["Target"].ToString() + "\"";
            //str += "}";

            str += (sdr["Leaf"].ToString().ToLower() == "false") ? ",\"state\":\"closed\"" : ",\"state\":\"open\"";
            str += "}";
        }
        sdr.Close();
        str += "]";

        return str;
    }

    /// <summary>
    /// 静态树菜单(网站_模块)
    /// </summary>
    /// <returns></returns>
    public static string GetJsonTreeStatic(string tn, string Level)
    {
        string where = " where IsDelete = 0";
        if (Level != "")
        {
            where = " where Grade<=" + Level + " and IsDelete = 0";
        }
        var sdr = dbHelper.ExecuteReader("select id,Name,Grade,Leaf,Target from " + tn + where + "  order by Levels");

        string str = "[{"; int pLevel = 1, cLevel = 1;
        while (sdr.Read())
        {
            cLevel = Convert.ToInt32(sdr["Grade"].ToString());
            //结束之前结点
            for (int i = 0; i < pLevel - cLevel; i++) str += "}]";
            //新父层出现
            if (pLevel > cLevel) str += "},{";
            //平层开始
            if (cLevel == pLevel && str.Length > 10) str += "},{";
            //子层开始
            if (cLevel > pLevel) str += ",\"children\":[{";

            str += "\"id\":\"" + sdr["id"].ToString() + "\"";
            str += ",\"text\":\"" + sdr["Name"].ToString() + "\"";
            str += (sdr["Leaf"].ToString()) == "True" ? ",\"iconCls\":\"icon-tree_leaf\"" : "";

            if (Convert.ToInt32(sdr["Grade"].ToString()) > 1)
            {
                str += (sdr["Leaf"].ToString().ToLower() == "false") ? ",\"state\":\"closed\"" : ",\"state\":\"open\"";
            }

            //temp += ",\"attributes\":{\"url\":\"" + sdr["链接"].ToString() + "\"";
            //temp += ",\"target\":\"" + sdr["Target"].ToString() + "\"";
            //temp += "}";

            pLevel = cLevel;
        }
        sdr.Close();
        //结束之前结点
        for (int i = 1; i < cLevel + 1; i++) str += "}]";
        return str;
    }
    public bool IsReusable
    {
        get
        {
            return false;
        }
    }
} 